﻿using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RedisSample.ViewComponents
{
    /// <summary>
    /// Page view counter view component.
    /// </summary>
    public class PageViewCounterViewComponent
        : ViewComponent
    {
        private readonly IDatabase _redis;
        public PageViewCounterViewComponent(IConnectionMultiplexer multiplexer)
        {
            _redis = multiplexer.GetDatabase();
        }
        public async Task<IViewComponentResult> InvokeAsync()
        {
            var controller = RouteData.Values["controller"] as string;
            var action = RouteData.Values["action"] as string;

            var rt = string.Empty;
            if (!string.IsNullOrEmpty(controller) && !string.IsNullOrEmpty(action))
            {
                var pageId = $"{controller}-{action}";

                await _redis.StringIncrementAsync(pageId);

                var pv = await _redis.StringGetAsync(pageId);
                rt = $"PageViews:{pv}";
            }
            return View<string>(rt);
        }
    }
}
